﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.ServiceModel.Activation;
using Microsoft.SharePoint.Client.Services;
using Microsoft.SharePoint;
using System.ServiceModel.Web;

using System.Xml.Linq;

using PIT.Labs.ProjectRepository.Owl2DotNet.Rdf;

namespace PIT.Labs.ProjectRepository.OntologyFeature.OntolgyXMLService
{
    /// <summary>
    /// Interface defining the calls that can be made to the ontology xml 
    /// export webservice
    /// </summary>
    [ServiceContract]
    public interface IOntologyXmlExport
    {
        /// <summary>
        /// Export the <see cref="SPList"/> with the given GUID in RDF/OWL XML 
        /// format
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/ExportByGuid?listid={guid}", Method = "GET")]
        XElement ExportByGuid(string guid);

        /// <summary>
        /// Export the <see cref="SPList"/> with the given name in RDF/OWL XML 
        /// format
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/ExportByName?listname={name}", Method = "GET")]
        XElement ExportByName(string name);
    }

    /// <summary>
    /// Implementation of the <see cref="IOntologyXmlExport"/> web service 
    /// contract
    /// </summary>
    [BasicHttpBindingServiceMetadataExchangeEndpoint]
    [AspNetCompatibilityRequirementsAttribute(RequirementsMode= AspNetCompatibilityRequirementsMode.Required)]
    public class OntologyXmlExport : IOntologyXmlExport
    {
        /// <summary>
        /// Export the <see cref="SPList"/> with the given GUID in RDF/OWL XML 
        /// format
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public XElement ExportByGuid(string guid)
        {
            var list = SPContext.Current.Web.Lists[new Guid(guid)];
            var ontology = OntologyHelper.GetOntology(new Guid(list.RootFolder.Properties["ontology::fileUri"].ToString()));

            var doc = OntologyHelper.SerializeList(list, ontology);
            
            return doc.Root;
        }

        /// <summary>
        /// Export the <see cref="SPList"/> with the given name in RDF/OWL XML 
        /// format
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public XElement ExportByName(string name)
        {
            var listguid = SPContext.Current.Web.Lists[name].ID;

            return ExportByGuid(listguid.ToString());
        }
    }
}
